package com.cango.qutz.web.auth.user.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.cango.framework.base.entity.DictEntity;
import com.cango.qutz.web.auth.user.dao.IUserDao;
import com.cango.qutz.web.entity.UserEntity;
import com.cango.framework.base.pagination.PageInfo;
import com.cango.framework.base.pagination.PaginationResult;
import com.cango.framework.base.util.MD5Util;
import com.cango.qutz.web.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cango.qutz.web.auth.user.service.IUserService;

@Service("userService")
public class UserServiceImpl implements IUserService {
    /** 用户sql的命名空间 */
    private static final String SQL_NAMESPACE = "user.";

    /** 新增用户的sql id */
    private static final String SQL_INSERT = "insertUser";

    /** 更新用户的sql id */
    private static final String SQL_UPDATE = "updateUser";

    /** 删除用户的sql id */
    private static final String SQL_DELETE = "deleteUser";

    /** 根据主键查询用户的sql id */
    private static final String SQL_QUERY_BY_ID = "queryUserById";

    /** 查询用户的sql id */
    private static final String SQL_QUERY_FOR_LIST = "queryUsers";

    /** 分页查询用户的sql id */
    private static final String SQL_QUERY_BY_PAGE = "queryUsersByPage";

    /** 根据登录名查询用户数量的sql id */
    private static final String SQL_QUERY_COUNT_BY_LOGIN = "selectCountByLogin";

    /** 查询所有有效部门的sql id */
    private static final String SQL_QUERY_DEPARTMENT_INFO = "queryDeptInfo";

    /** 查询所有有效部门的sql id */
    private static final String SQL_INSERT_USER_POSITION = "insertUserPosition";

    /** 查询所有有效部门的sql id */
    private static final String SQL_UPDATE_USER_POSITION = "updateUserPosition";

    /** 用户修改个人信息sql id */
    private static final String SQL_UPDATE_EDIT_PERSON = "editPerson";

    /** 查询用户信息及其所属企业 */
    private static final String SQL_QUERY_ORG_INFO = "queryOrgByUserId";

    @Autowired
    private IUserDao userDao;

    @Override
    public int insert(UserEntity user) {
        /*
         * 用户新增：岗位需要写入关联表：tr_auth_user_position中 初始密码未111111加密后存入 工号：页面录入；用户类型：P 应用用户
         */
        String psw = MD5Util.md5("111111");
        String password = MD5Util.apr1Crypt(psw, user.getLoginId());
        user.setPassword(password);
        user.setUserType("P");
        user.setIsDel(0);
        int id = userDao.insert(SQL_NAMESPACE + SQL_INSERT, user);
        // 保存用户岗位关联关系
        if (null != user.getPositionCode() && !"".equals(user.getPositionCode())) {
            this.userDao.insert(SQL_NAMESPACE + SQL_INSERT_USER_POSITION, user);
        }

        //更新系统权限

        insertUserSysRel(user.getUserId(),user.getClientCode());

        return id;
    }

    @Override
    public int update(UserEntity user) {
        UserEntity userEdit = this.queryObjectById(user.getUserId());
        userEdit.setUserName(user.getUserName());
        userEdit.setDeptCode(user.getDeptCode());
        userEdit.setAgentNo(user.getAgentNo());
        userEdit.setMobilephone(user.getMobilephone());
        userEdit.setEmail(user.getEmail());
        userEdit.setWeixin(user.getWeixin());
        userEdit.setStatus(user.getStatus());
        userEdit.setUpdateUser(user.getUpdateUser());
        userEdit.setUpdateTime(new Date());
        this.userDao.update(SQL_NAMESPACE + SQL_UPDATE, userEdit);
        //更新系统权限
        insertUserSysRel(user.getUserId(),user.getClientCode());

        // 岗位修改
        return this.userDao.update(SQL_NAMESPACE + SQL_UPDATE_USER_POSITION, user);
    }
    private void insertUserSysRel(Integer userId,String [] clientCodes){
        HashMap<String,Object> param = new HashMap<String,Object>();
        //删除已不需要授权的系统
        param.put("userId",userId);
        userDao.delete(SQL_NAMESPACE + "deleteUserSysRel",param);

        if(null == clientCodes){
            return;
        }

        for(String clientCode : clientCodes){
            param.put("clientCode",clientCode);
            userDao.insert(SQL_NAMESPACE + "insertUserSysRel",param);
        }
    }

    @Override
    public int delete(UserEntity user) {
        return userDao.delete(SQL_NAMESPACE + SQL_DELETE, user);
    }

    @Override
    public UserEntity queryObjectById(Integer userId) {
        return userDao.queryObjectById(SQL_NAMESPACE + SQL_QUERY_BY_ID, userId);
    }

    @Override
    public List<UserEntity> queryList(Object param) {
        return userDao.queryList(SQL_NAMESPACE + SQL_QUERY_FOR_LIST, param);
    }

    @Override
    public PaginationResult<UserEntity> queryListByPage(UserEntity param, PageInfo pageinfo) {
        return userDao.queryListByPage(SQL_NAMESPACE + SQL_QUERY_BY_PAGE, param, pageinfo);
    }

    @Override
    public boolean validLoginId(String loginId) {
        int count = this.userDao.queryCountByLogin(SQL_NAMESPACE + SQL_QUERY_COUNT_BY_LOGIN, loginId);
        return count > 0 ? false : true;
    }

    @Override
    public UserEntity getOrgInfoByUserId(Integer userId) {
        return userDao.queryForObject(SQL_NAMESPACE + SQL_QUERY_ORG_INFO, userId);
    }

//    @Override
//    public List<Department> queryDeptInfo() {
//        return this.userDao.queryList(SQL_NAMESPACE + SQL_QUERY_DEPARTMENT_INFO, "");
//    }

    @Override
    public void editPersonalInfo(UserEntity user) {
        UserEntity userEdit = this.queryObjectById(user.getUserId());
        userEdit.setUserName(user.getUserName());
        userEdit.setMobilephone(user.getMobilephone());
        userEdit.setEmail(user.getEmail());
        userEdit.setWeixin(user.getWeixin());
        userEdit.setUpdateUser(user.getUpdateUser());
        userEdit.setUpdateTime(new Date());
        this.userDao.update(SQL_NAMESPACE + SQL_UPDATE, userEdit);
    }


    @Override
    public List<DictEntity> getUserSys(Long userId) {
        return this.userDao.queryList(SQL_NAMESPACE + "getUserSys", userId);
    }
}
